package com.cti.ftpservice.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.cti.ftpservice.dao.FtpFileDao;
import com.cti.ftpservice.dao.OnixDataDao;
import com.cti.ftpservice.model.onix.FtpFileInfo;
import com.cti.ftpservice.service.FtpFileInfoService;
import com.cti.ftpservice.utils.FileHelper;
import com.cti.ftpservice.vo.FtpFileDownloadViewVo;
import com.cti.ftpservice.vo.FtpFileInfoViewVo;
import com.cti.ftpservice.vo.PageViewVO;
import com.cti.ftpservice.vo.ParameterVo;


@Service("ftpFileInfoService")
public class FtpFileInfoServiceImpl implements FtpFileInfoService {

	@Resource
	private FtpFileDao ftpFileDao;
	
	@Resource
	private OnixDataDao onixDataDao;

	
	private static Log log = LogFactory.getLog(FtpFileInfoServiceImpl.class);
	
	@Override
	public void addFtpFileViewVo(FtpFileInfoViewVo ftpFileVo) {
		try {
			FtpFileInfo ftpFileInfo=null;
			if(!ftpFileVo.getLocalFtpFilePath().isEmpty())
			    ftpFileInfo=ftpFileDao.getFileInfoByFileName(ftpFileVo.getFileName()); //本地存储路径唯一确定一条记录
			if(ftpFileInfo!=null)
				return;
			ftpFileInfo =new FtpFileInfo();
	        BeanUtils.copyProperties(ftpFileVo,ftpFileInfo,"id");
	        ftpFileInfo.setCreateDate(new Date());
			ftpFileDao.addFtpFile(ftpFileInfo);
			
		} catch (Exception e) {
			log.error("添加ftpinfo文件记录出错："+e.getMessage());
		}
		
	}
	
	public void addFtpFileViewVos(List<FtpFileInfoViewVo> ftpFileVos){
		if(ftpFileVos==null||ftpFileVos.size()==0)
			return;
		for (FtpFileInfoViewVo ftpFileInfoViewVo : ftpFileVos) {
			addFtpFileViewVo(ftpFileInfoViewVo);
		}
	}

	@Override
	public String addOrUpdateFtpFileViewVo(FtpFileInfoViewVo ftpFileVo) {
		try {
				FtpFileInfo ftpFileInfo=null;
				if(ftpFileVo.getId()!=null)
					ftpFileInfo=ftpFileDao.getFileInfoById(ftpFileVo.getId());
				if(ftpFileInfo==null&&!ftpFileVo.getLocalFtpFilePath().isEmpty())
				    ftpFileInfo=ftpFileDao.getFileInfoByFileName(ftpFileVo.getFileName()); //文件名唯一确定一条记录
				if(ftpFileInfo==null){
					ftpFileInfo=new FtpFileInfo();
					ftpFileInfo.setCreateDate(new Date());
				}else{
					if(ftpFileInfo.getParsed())
						return ftpFileInfo.getId();
				}
				BeanUtils.copyProperties(ftpFileVo,ftpFileInfo,"id","totalRecordCount","parsed","parsedResult","parsedDate");
				if(ftpFileVo.getTotalRecordCount()>0)
					ftpFileInfo.setTotalRecordCount(ftpFileVo.getTotalRecordCount());
				if(ftpFileInfo!=null){
					int currentSaveCount=onixDataDao.getParsedCountByFtpInfoId(ftpFileInfo.getId());
					ftpFileInfo.setSaveRecordCount(currentSaveCount);
					ftpFileInfo.setParsedDate(new Date());
					if(ftpFileInfo.getTotalRecordCount()>0&&ftpFileInfo.getTotalRecordCount()==ftpFileInfo.getSaveRecordCount()){
						ftpFileInfo.setParsed(true);
						ftpFileInfo.setParsedResult("系统解析文件成功：共保存或更新数据"+ftpFileInfo.getTotalRecordCount()+"条");
					}
				}
				ftpFileDao.addOrUpdateFtpFileInfo(ftpFileInfo);
				return ftpFileInfo.getId();
		} catch (Exception e) {
			log.error("添加文件信息出错："+ftpFileVo.getLocalFtpFilePath()+":"+e.getMessage());
		}
		return null;
	}
	
	public void addOrUpdateFtpFileViewVos(FtpFileInfoViewVo[] ftpFileVos){
		if(ftpFileVos==null||ftpFileVos.length==0)
			return;
		for (FtpFileInfoViewVo ftpFileInfoViewVo : ftpFileVos) {
			addOrUpdateFtpFileViewVo(ftpFileInfoViewVo);
		}
	}
	
	

	@Override
	public void deleteFtpFileViewVo(String ftpFileId) {
		if(!StringUtils.isBlank(ftpFileId)){
		   FtpFileInfo ftpFileInfo= ftpFileDao.getFileInfoById(ftpFileId);
		   if(ftpFileInfo!=null){
			   ftpFileDao.deleteFtpFile(ftpFileInfo);
		   }
		}
	}

	@Override
	public List<FtpFileInfoViewVo> getFtpFileInfoViewVosByFtpServiceId(String ftpServiceId, Boolean approvedByHuman) {
		List<FtpFileInfoViewVo> ftpVos= new ArrayList<FtpFileInfoViewVo>();
		List<FtpFileInfo> ftpFileInfos = ftpFileDao.getFtpFileInfosByFtpServiceIdAndApprovedHuman(ftpServiceId, approvedByHuman);
		if(ftpFileInfos!=null && ftpFileInfos.size()>0){
			for(FtpFileInfo ftpFile :ftpFileInfos){
				FtpFileInfoViewVo viewVo=converFtpFileInfoToFtpFileInfoViewVo(ftpFile);
				ftpVos.add(viewVo);
			}
		}
		return ftpVos;
	}
	
	private FtpFileInfoViewVo converFtpFileInfoToFtpFileInfoViewVo(FtpFileInfo ftpFile){
		FtpFileInfoViewVo viewVo=  new FtpFileInfoViewVo();
		BeanUtils.copyProperties(ftpFile, viewVo);
		return viewVo;
	}

	@Override
	public PageViewVO<FtpFileInfoViewVo> getFtpFileInfoViewVoByParams(ParameterVo[] paramVos,int pageIndex,int pageSize) {
		PageViewVO<FtpFileInfoViewVo> pgVo = new PageViewVO<FtpFileInfoViewVo>();
		PageViewVO<FtpFileInfo> pg=ftpFileDao.getFtpFileInfoViewVoByParams(paramVos,pageIndex,pageSize);
		List<FtpFileInfoViewVo> fileInfoViewVos= new ArrayList<FtpFileInfoViewVo>();
		if(pg.getDatas()!=null && pg.getDatas().size()>0){
			for(FtpFileInfo ftpFile :pg.getDatas()){
				FtpFileInfoViewVo viewVo=converFtpFileInfoToFtpFileInfoViewVo(ftpFile);
				fileInfoViewVos.add(viewVo);
			}
		}
		pgVo.setCurrentPageIndex(pg.getCurrentPageIndex());
		pgVo.setPageRecordSize(pg.getPageRecordSize());
		pgVo.setTotalPageCount(pg.getTotalPageCount());
		pgVo.setTotalRecordCount(pg.getTotalRecordCount());
		pgVo.setDatas(fileInfoViewVos);
		return pgVo;
	}

	public List<FtpFileInfoViewVo> getOnixUnDealXmlFiles() {
		 List<FtpFileInfoViewVo> viewVos=new ArrayList<FtpFileInfoViewVo>();
		 List<FtpFileInfo> fileInfos=ftpFileDao.getUnDealFileInfosByFileType(FtpFileInfo.FtpServiceType_OnixDownloadFile);
		 if(fileInfos!=null&&fileInfos.size()>0){
			 for (FtpFileInfo ftpFileInfo : fileInfos) {
				viewVos.add(converFtpFileInfoToFtpFileInfoViewVo(ftpFileInfo));
			}
		 }
		 return viewVos;
	}

	@Override
	public void saveFtpFileInfoApprovedResult(String[] ftpFileIds,Boolean enable, String approvedResult,String approvedUserId) {
	   if(ftpFileIds!=null && ftpFileIds.length>0){
		   if(StringUtils.isBlank(approvedUserId))
			   throw new RuntimeException("审读人ID不能为null！");
		   for(String ftpFileId :ftpFileIds){
			   FtpFileInfo ftpFileInfo = ftpFileDao.getFileInfoById(ftpFileId);
			   if(ftpFileInfo==null) continue;
			   ftpFileInfo.setParsed(enable);
			   ftpFileInfo.setParsedDate(new Date());
			   ftpFileInfo.setParsedResult(approvedResult);
			   ftpFileDao.addOrUpdateFtpFileInfo(ftpFileInfo);
		   }
	   }
	}

	@Override
	public List<FtpFileDownloadViewVo> getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(String ftpServiceId, String[] downloadPaths) {
		List<FtpFileDownloadViewVo> viewVos= new ArrayList<FtpFileDownloadViewVo>();
		if(downloadPaths!=null && downloadPaths.length>0){
			for(String downloadPath :downloadPaths){
				List<FtpFileInfo> downloadFiles= ftpFileDao.getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(downloadPath);
				if(downloadFiles!=null && downloadFiles.size()>0){
					for(FtpFileInfo fileInfo :downloadFiles){
						FtpFileDownloadViewVo vo= new FtpFileDownloadViewVo();
						vo.setDownloadFtpFilePath(fileInfo.getLocalFtpFilePath());
		                vo.setDownloadFtpFileSize(fileInfo.getFileSize());
		                viewVos.add(vo);
					}
				}
			}
		}else{
			List<FtpFileInfo> downloadFiles= ftpFileDao.getFtpDownloadFileViewVoByFtpServiceIdAndDownloadPath(null);
			if(downloadFiles!=null && downloadFiles.size()>0){
				for(FtpFileInfo fileInfo :downloadFiles){
					FtpFileDownloadViewVo vo= new FtpFileDownloadViewVo();
					vo.setDownloadFtpFilePath(fileInfo.getLocalFtpFilePath());
	                vo.setDownloadFtpFileSize(fileInfo.getFileSize());
	                viewVos.add(vo);
				}
			}
		}
		return viewVos;
	}

	@Override
	public List<String> getFtpFileInfoExtensions() {
		return ftpFileDao.getFtpFileInfoExtensions();
	}
	
	
	public boolean updateFtpFileinfoParsedCount(String ftpfileInfoId,int totalRecordCount,String parsingResult){
		boolean finishedParsed=false;
		try {
			if(totalRecordCount<=0)
				return finishedParsed;
			FtpFileInfo ftpFileInfo=ftpFileDao.getFileInfoById(ftpfileInfoId);
			if(ftpFileInfo!=null&&ftpFileInfo.getId()!=null){
				if(ftpFileInfo.getParsed()&&ftpFileInfo.getSaveRecordCount()>0)
					return true;
				int currentSaveCount=onixDataDao.getParsedCountByFtpInfoId(ftpfileInfoId);
				if(totalRecordCount>0)
					ftpFileInfo.setTotalRecordCount(totalRecordCount);
				ftpFileInfo.setSaveRecordCount(currentSaveCount);
				ftpFileInfo.setParsedDate(new Date());
				if(ftpFileInfo.getTotalRecordCount()==ftpFileInfo.getSaveRecordCount()){
					ftpFileInfo.setParsed(true);
					ftpFileInfo.setParsedResult("文件解析成功！"+parsingResult);
					finishedParsed=true;
				}else{
					ftpFileInfo.setParsedResult(parsingResult);
				}
				ftpFileDao.addOrUpdateFtpFileInfo(ftpFileInfo);
			}
		} catch (Exception e) {
			log.error("更新FTPFileInfo文件出错："+e.getMessage());
		}
		return finishedParsed;
	}
	
	public void updateSuccessFulParsedAndSaveToDataBaseFtpFileInfo(String ftpfileInfoId,int totalCount,int repeatRecordCount){
		try {
			FtpFileInfo ftpFileInfo=ftpFileDao.getFileInfoById(ftpfileInfoId);
			if(ftpFileInfo==null)
				return;
			ftpFileInfo.setParsed(true);
			ftpFileInfo.setParsedDate(new Date());
			int redeadySaveCount=onixDataDao.getParsedCountByFtpInfoId(ftpfileInfoId);
			ftpFileInfo.setSaveRecordCount(redeadySaveCount);
			ftpFileInfo.setTotalRecordCount(totalCount);
			ftpFileInfo.setParsedResult("文件解析成功：共保存或更新数据："+redeadySaveCount+"条;重复数据："+repeatRecordCount+"条");
			ftpFileDao.addOrUpdateFtpFileInfo(ftpFileInfo);
		} catch (Exception e) {
			log.error("更新FTPFileInfo文件出错："+e.getMessage());
		}
	}

	public void updateUnSuccessFulParsed(String ftpfileInfoId,String  failureReason){
		try {
			FtpFileInfo ftpFileInfo=ftpFileDao.getFileInfoById(ftpfileInfoId);
			if(ftpFileInfo==null)
				return;
			ftpFileInfo.setParsed(true);
			ftpFileInfo.setParsedDate(new Date());
			ftpFileInfo.setParsedResult(failureReason);
			ftpFileDao.addOrUpdateFtpFileInfo(ftpFileInfo);
		} catch (Exception e) {
			log.error("更新FTPFileInfo文件出错："+e.getMessage());
		}
	}
	@Override
	public  List<FtpFileInfoViewVo> updateUnFinishedParsingFtpFileInfo() {
		List<FtpFileInfoViewVo> fileInfoViewVos=new ArrayList<FtpFileInfoViewVo>();
		List<FtpFileInfo> unFileInfos=ftpFileDao.getUnDealFileInfosByFileType(FtpFileInfo.FtpServiceType_OnixDownloadFile);
		for (FtpFileInfo ftpFileInfo : unFileInfos) {
			boolean finished=updateFtpFileinfoParsedCount(ftpFileInfo.getId(), ftpFileInfo.getTotalRecordCount(),"");
			if(!finished){
				fileInfoViewVos.add(converFtpFileInfoToFtpFileInfoViewVo(ftpFileInfo));
			}
		}
		return fileInfoViewVos;
	}

}
